package com.example.module_motocircle.ui.post.detail.adapter

import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.example.lib_common.Router.Ui.TopicActivity
import com.example.lib_common.dp
import com.example.lib_common.getAliOSSVideoImage
import com.example.lib_common.utils.Info
import com.example.lib_common.utils.ToastUtils
import com.example.lib_image.GlideApp
import com.example.module_motocircle.R
import com.example.module_motocircle.databinding.ItemPostDetailBinding
import com.example.module_motocircle.model.PostItem
import com.example.module_motocircle.model.PostModel
import com.example.module_motocircle.model.Topic
import com.example.module_motocircle.ui.post.adapter.setLandscape
import com.example.module_motocircle.ui.post.adapter.setPortrait
import com.google.android.exoplayer2.util.MimeTypes

class PostDetailsViewHolder(
    itemView: View,
    private val onImageClick: ((Int, Int, List<String>, List<Info>) -> Unit)? = null,
    private val onUserClick: ((String, Boolean) -> Unit)? = null,
    private val onFollowClick: ((post: PostModel) -> Unit)? = null,
) : RecyclerView.ViewHolder(itemView) {
    private val mBinding: ItemPostDetailBinding by lazy {
        DataBindingUtil.getBinding(this.itemView)!!
    }
    lateinit var postModel: PostModel

    var isClickSpan: Boolean = false


    fun initView(post: PostModel, position: Int) {

        mBinding.apply {
            handlePicOrVideo(post, position)
            Log.d("sss", post.model_name.toString())
            Log.d("sss", post.content.toString())
            //handlePicOrVideo(post)
            postModel = post
            //处理帖子中携带的话题
            if (!post.topics.isNullOrEmpty())
                handleTopic(post)
            tvUsername.text = post.model_name
            tvPublishTime.text=post.list_show_time
        }
    }

    private fun ItemPostDetailBinding.handlePicOrVideo(post: PostModel, position: Int) {
        post.image ?: return
        if (post.image.size == 1 && MimeTypes.isVideo(post.image[0].contentType)) {
            //视频
            nineGridView.visibility = View.GONE
            lVideo.visibility = View.VISIBLE
            lVideo.setOnClickListener {
                //VideoPlayerActivity.jump(post.img[0].url)
            }
            val l = lVideo.layoutParams
            val video = post.image.firstOrNull() ?: return
            val videoHeight = video.imageHeight
            val videoWidth = video.imageWidth
            if (videoHeight != null) {
                if (videoHeight > videoWidth!!) {
                    l.width = 233.dp
                    l.height = 311.dp
                } else {
                    l.width = 343.dp
                    l.height = 180.dp
                }
            }
            lVideo.layoutParams = l
            GlideApp.with(this.root).load(post.image[0].url)
                .circleCrop()
                .into(ivVideo)
        } else {
            nineGridView.visibility = View.VISIBLE
            lVideo.visibility = View.GONE
            //图片
            nineGridView.setPicsList(post.image)
            onImageClick?.let {
                //nineGridView.setOnItemClickListener(onImageClick)
            }
            nineGridView.initView()
        }
    }
private fun handleTopic(postItem: PostModel) {
    val content = postItem.content
    val spannableStringBuilder = SpannableStringBuilder(content)
    //保存话题的起始位置
    val topicIndexMap = mutableMapOf<String,MutableList<Int>>() //键:话题内容 值:话题开始和结束的位置
    //保存话题的id
    val topicIdMap = mutableMapOf<String,String>()//键:话题内容 值:话题id

    val topics = postItem.topics
    topics?.forEach{
        //话题前后加#
        val topicName = String.format("#%s#",it.topicName)
        //找的内容
        var temp = content

        while (true){
            val start = temp?.indexOf(topicName)
            if(start!! > -1){ //找到了
                if(topicIndexMap[topicName] == null){
                    topicIndexMap[topicName] = mutableListOf()
                }
                topicIndexMap[topicName]?.add(start)
                topicIndexMap[topicName]?.add(start+topicName.length)
                topicIdMap[topicName] = it.topicId.toString()
            }else{ //没找到
                break
            }
            //继续从后面开始找
            temp = temp?.substring(start+topicName.length)
        }
    }
    //今日份车溜子#日常溜车#   #日常溜车#   topicIndexMap:"#日常溜车#":[6,11]    topicIdMap:"#日常溜车#":"1643118469338963969"
    Log.d("handleTopic", "内容: $content")
    Log.d("handleTopic", "起始位置: $topicIndexMap")
    Log.d("handleTopic", "id: $topicIdMap")
    //富文本
    topicIndexMap.forEach{name,list ->
        spannableStringBuilder.setSpan(object : ClickableSpan(){
            override fun onClick(widget: View) {
                ToastUtils.showLong(itemView.context,"点击了话题id ${topicIdMap[name]}")
            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = ContextCompat.getColor(itemView.context, R.color.topic)
                ds.isUnderlineText = false
            }

        },list[0],list[1], SpannableStringBuilder.SPAN_EXCLUSIVE_INCLUSIVE)
    }
    mBinding.tvPostContent.apply {
        movementMethod = LinkMovementMethod.getInstance()
        highlightColor = Color.TRANSPARENT
        text = spannableStringBuilder

    }
}

    fun clickUser() {
        if (postModel.isOfficial()) return
        onUserClick?.invoke(postModel.createBy, postModel.isOfficial())
    }

    fun clickFollow() {
        onFollowClick?.invoke(postModel)
    }
}
